import {
  getUserDet,
  getAppSysPerm,
  getMenuAuth,
  getDataAuth,
  saveAccount,
  accountDisable,
  addAccount,
  queryRoleName,
} from '../services/api';
import { message } from 'antd';

export default {
  namespace: 'auth',

  state: {
    AppSysPerm: [],
    MenuAuth: [],
    DataAuth: [],
    userInfo: {},
    roleName: [],
  },

  effects: {
    *fetchUser({ payload }, { call, put }) {
      const response = yield call(getUserDet, payload);
      //console.log('userdetail', response);
      yield put({
        type: 'saveUser',
        payload: response.amAccountDet,
      });
    },
    *fetchApp(_, { call, put }) {
      const response = yield call(getAppSysPerm);
      //console.log('response', response);
      yield put({
        type: 'saveApp',
        payload: response.appSysPerm,
      });
    },
    *fetchMenuAuth({ payload, callback }, { call, put }) {
      const response = yield call(getMenuAuth, payload);
      //console.log('response', response);
      yield put({
        type: 'saveMenu',
        payload: response.amMenuPerm,
      });
      if (callback) callback();
    },
    *fetchDataAuth({ payload, callback }, { call, put }) {
      const response = yield call(getDataAuth, payload);
      //console.log('response', response);
      yield put({
        type: 'saveData',
        payload: response.amDataPerm,
      });
      if (callback) callback();
    },
    *fetchName({ payload }, { call, put }) {
      const response = yield call(queryRoleName);
      //console.log('roleName', response);
      if (response?.roleNameCodes)
        yield put({
          type: 'saveName',
          payload: response.roleNameCodes,
        });
    },
    *saveAccount({ payload, callback }, { call }) {
      const response = yield call(saveAccount, payload);
      //console.log('response', response);
      if (response?.result?.code === 2001) {
        message.error('提交出错，请检查');
      } else if (callback) callback();
    },
    *addAccount({ payload, callback }, { call }) {
      const response = yield call(addAccount, payload);
      //console.log('response', response);
      if (response?.result?.code === 2001) {
        message.error('提交出错，请检查');
      } else if (callback) callback();
    },
  },

  reducers: {
    saveUser(state, action) {
      return {
        ...state,
        userInfo: action.payload,
      };
    },
    saveApp(state, action) {
      return {
        ...state,
        AppSysPerm: action.payload,
      };
    },
    saveMenu(state, action) {
      return {
        ...state,
        MenuAuth: action.payload,
      };
    },
    saveData(state, action) {
      return {
        ...state,
        DataAuth: action.payload,
      };
    },
    saveName(state, action) {
      return {
        ...state,
        roleName: action.payload,
      };
    },
  },
};
